<template>
  <el-dialog v-model="visible" title="上传文件" :close-on-click-modal="false" :close-on-press-escape="false">
    <el-upload
      :action="url"
      :file-list="fileList"
      drag
      multiple
      :before-upload="beforeUploadHandle"
      :on-success="successHandle"
      class="text-center">
      <i class="el-icon-upload"></i>
      <div class="el-upload__text" v-html="'将文件拖到此处，或<em>点击上传</em>'"></div>
      <div class="el-upload__tip" slot="tip">只支持jpg、png、gif格式文件！</div>
    </el-upload>
  </el-dialog>
</template>

<script setup>
import Cookies from 'js-cookie'

import {ref} from "vue";
import {message} from "../../../utils/commonScript.js";

const emit = defineEmits(['refreshDataList'])

const visible = ref(false)
const url = ref('')
const num = ref(0)
const fileList = ref([])

const init = () => {
	visible.value = true
	url.value = `${window.SITE_CONFIG['apiURL']}/sys/oss/upload?token=${Cookies.get('token')}`
	num.value = 0
	fileList.value = []
}
// 上传之前
const beforeUploadHandle = (file)=>{
	if (file.type !== 'image/jpg' && file.type !== 'image/jpeg' && file.type !== 'image/png' && file.type !== 'image/gif') {
		message.error('只支持jpg、png、gif格式文件！')
		return false
	}
	num.value++
}
// 上传成功
const successHandle = (res, file, fileList) => {
	if (res.code !== 0) {
		return message.error(res.msg)
	}
	fileList.value = fileList
	num.value--
	if (num.value === 0) {
		message({
			message: '操作成功',
			type: 'success',
			duration: 500,
			onClose: () => {
				visible.value = false
				emit('refreshDataList')
			}
		})
	}
}
defineExpose({
	init
})
</script>
